package cn._51doit.flink.day02.transformations;

import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

/**
 * 不直接使用filter算子，而是调用transform，实现类似的功能
 */
public class FilterDemo2 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //spark hadoop
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<String> filtered = lines.transform("MyFilter", TypeInformation.of(String.class), new MyStreamFilter());

        filtered.print();

        env.execute();
    }

    private static class MyStreamFilter extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String> {

        @Override
        public void processElement(StreamRecord<String> element) throws Exception {

            String in = element.getValue();
            if (in.startsWith("s")) {
                output.collect(element);
            }

        }
    }
}
